<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import { fetchCreateRfid, fetchUpdateRfid } from '@/service/api/system/rfid';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { useDict } from '@/hooks/business/dict';import { $t } from '@/locales';

defineOptions({
  name: 'RfidOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.System.Rfid | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { options: cmdRfidStatusOptions } = useDict('cmd_rfid_status');

const { formRef, validate, restoreValidation } = useNaiveForm();
const { createRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增rfid管理',
    edit: '编辑rfid管理'
  };
  return titles[props.operateType];
});

type Model = Api.System.RfidOperateParams;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
      rfid: '',
      status: '',
  };
}

type RuleKey = Extract<
  keyof Model,
  | 'rfid'
  | 'status'
  | 'createDept'
  | 'createTime'
  | 'createBy'
  | 'updateTime'
  | 'updateBy'
  | 'delFlag'
  | 'version'
  | 'tenantId'
>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  rfid: createRequiredRule('rfid不能为空'),
  status: createRequiredRule('使用状态不能为空'),
  createDept: createRequiredRule('创建部门不能为空'),
  createTime: createRequiredRule('创建时间不能为空'),
  createBy: createRequiredRule('创建人不能为空'),
  updateTime: createRequiredRule('更新时间不能为空'),
  updateBy: createRequiredRule('更新人不能为空'),
  delFlag: createRequiredRule('删除标志不能为空'),
  version: createRequiredRule('版本不能为空'),
  tenantId: createRequiredRule('租户编号不能为空')
};

function handleUpdateModelWhenEdit() {
  if (props.operateType === 'add') {
    Object.assign(model, createDefaultModel());
    return;
  }

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  const { id, rfid, status } = model;

  // request
  if (props.operateType === 'add') {
    const { error } = await fetchCreateRfid({ rfid, status });
    if (error) return;
  }

  if (props.operateType === 'edit') {
    const { error } = await fetchUpdateRfid({ id, rfid, status });
    if (error) return;
  }

  window.$message?.success($t('common.updateSuccess'));
  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    handleUpdateModelWhenEdit();
    restoreValidation();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" :title="title" display-directive="show" :width="800" class="max-w-90%">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem label="rfid" path="rfid">
          <NInput v-model:value="model.rfid" placeholder="请输入rfid" />
        </NFormItem>
        <NFormItem label="使用状态" path="status">
          <NRadioGroup v-model:value="model.status">
            <NSpace>
              <NRadio
                v-for="option in cmdRfidStatusOptions"
                :key="option.value"
                :value="option.value"
                :label="option.label"
              />
            </NSpace>
          </NRadioGroup>
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
